<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>

    <style>
        .el-header, .el-footer {
            background-color: #B3C0D1;
            color: #333;
            text-align: center;
            line-height: 60px;
        }

        .el-aside {
            background-color: #ffffff;
            color: #333;
            text-align: center;
            line-height: 200px;
        }

        .el-main {
            background-color: #99a9bf;
            color: #333;
            text-align: center;
            line-height: 160px;
        }

        body > .el-container {
            margin-bottom: 40px;
        }

        .el-container:nth-child(5) .el-aside,
        .el-container:nth-child(6) .el-aside {
            line-height: 260px;
        }

        .el-container:nth-child(7) .el-aside {
            line-height: 320px;
        }

        /*#clearBtn {*/
        /*    position: relative;*/
        /*    top: 50%; !*偏移*!*/
        /*    transform: translateY(50%);*/
        /*    text-align: center;*/
        /*}*/

    </style>
</head>
<body>
<div style="text-align: center">
    <div>
        <h2>欢迎来到ChatDemo聊天室！</h2>
    </div>
</div>

<div id="main_body" style="padding-left: 250px;padding-right: 250px">
    <el-container>
        <el-header>
            <span style="float: left">登录用户：{{user.userName}}</span>
            <span v-show="targetBoolean" style="text-align: center;color: green">正在和{{targetUser}}聊天</span>
            <span style="float: right">状态：在线</span>
        </el-header>
        <el-main>
            <el-container style="height: 500px">
                <el-main>
                    <!--根据条件判断是否打开聊天室对话框-->
                    <!--当前登录用户是否选择一名好友进行聊天-->
                    <!--                        <img style="height: 100%;width: 100%" v-if=chatOpenBoolean src="../static/image/pexels-burst-374870.jpg">-->
                    <div v-if="chatOpenBoolean" style="background-image: url(../static/image/pexels-burst-374870.jpg);
                        height: 100%;width: 100%;background-size: 100% 100%;font-size: 28px">
                        基于WebSocket实现聊天室功能
                    </div>
                    <el-container v-else>
                        <el-main id="content" style="height: 360px;background-color: white">
                            <!--发送发-->
                            <!--<div id="fromUser" style="float: right;width: 540px;padding-top: 30px;padding-bottom: 30px">
                                <div style="width: 60px;float: right;padding-left: 25px;height: 50px;line-height: 50px">
                                    &lt;!&ndash;<el-avatar :size=50> {{user.userName}} </el-avatar>&ndash;&gt;
                                    <img style="height: 50px;width: 50px;border-radius:50%; " src="../static/image/headImg/pexels-aviv-perets-3274903.jpg">
                                </div>
                                <div style="float: right;background-color: cornflowerblue;border-radius: 4px;line-height: 24px;letter-spacing: 1px;max-width: 455px">
                                    聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容
                                </div>
                            </div>-->
                            <!--接收方-->
                            <!--<div id="toUser" style="float: left;width: 540px;">
                                <div style="width: 60px;float: left;padding-right: 25px;height: 50px;line-height: 50px">
                                    <el-avatar :size=50> {{targetUser}} </el-avatar>
                                </div>
                                <div style="float: left;background-color: cornflowerblue;border-radius: 4px;line-height: 24px;letter-spacing: 1px;max-width: 455px">
                                    聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容聊天内容
                                </div>
                            </div>-->
                        </el-main>
                        <el-footer style="height: 100px">
                            <el-input
                                    type="textarea"
                                    :autosize="{ minRows: 1, maxRows: 1}"
                                    placeholder="请输入内容"
                                    v-model="textarea">
                            </el-input>
                            <div style="text-align: right;height: 40px;">
                                <el-button id="clearBtn" style="vertical-align: middle" size="mini">清空</el-button>
                                <el-button @click="sendMessageToTargetUser" size="mini" type="primary">发送</el-button>
                            </div>
                        </el-footer>
                    </el-container>
                </el-main>
                <el-aside width="200px">
                    <el-container>
                        <el-header style="height: 220px;background-color: white">
                            <span>好友列表</span>
                            <div v-for="simpleUser in onLineUser" v-show="simpleUser!==user.userName" style="height: 35px;
                                width: 100%;vertical-align: middle;text-align: left;line-height: 35px">
                                <el-link @click="openDialog(simpleUser)" :underline="false">{{simpleUser}}</el-link>
                                <!--{{simpleUser}}-->
                            </div>
                        </el-header>
                        <el-divider></el-divider>
                        <el-header style="height: 220px;background-color: white">
                            <span>通知栏</span>
                            <div v-for="message in broadcastMessage" style="height: 25px;text-align: left">{{message}}
                            </div>
                        </el-header>
                    </el-container>
                </el-aside>
            </el-container>
        </el-main>
    </el-container>
</div>

</body>
<!--引入资源文件-->
<!--vue-->
<!--element-ui-->
<!--axios-->
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>

<!--vue实例-->
<script>
    new Vue({
        el: "#main_body",
        data() {
            return {
                user: {
                    userName: "",
                },
                //好友列表
                onLineUser: [],
                //系统通知栏
                broadcastMessage: [],
                chatOpenBoolean: true,
                //正在和目标用户聊天
                targetUser:"",
                targetBoolean: false,
                textarea: ""
            }
        },
        methods: {
            //获取已登录用户信息
            getUserInfo() {
                var token = sessionStorage.getItem("user");
                let _this = this
                axios.get(`http://localhost:8080/user/getUserInfo/${token}`).then(function (res) {
                    console.log(res)
                    _this.user.userName = res.data
                    _this.initWebSocket()
                })
            },

            //初始化WebSocket连接
            initWebSocket() {
                let _this = this
                var host = window.location.host;
                //获取域名：localhost:8080
                console.log("获取的域名为：" + host)
                let webSocket = new WebSocket("ws://" + host + "/chat/" + this.user.userName);
                //将webSocket实例对象挂载到Vue实例上来进行全局访问
                Vue.prototype.$webSocket = webSocket
                //给websocket连接绑定事件
                webSocket.onopen = function () {
                    //成功建立websocket连接之后需要做什么事
                }
                //客户端接收服务端推送的消息
                webSocket.onmessage = function (event) {
                    var dataStr = event.data;
                    var obj = JSON.parse(dataStr);
                    console.log("广播消息为：" + obj.message)
                    console.log(dataStr);
                    //判断接收的消息是否为系统消息
                    if (obj.isSystem) {
                        //1、展示当前在线用户
                        _this.onLineUser = obj.toUserName
                        //2、发送广播消息
                        console.log(obj.message)
                        _this.broadcastMessage.unshift(obj.message)
                    } else {
                        var str = "<div style=\"float: left;width: 540px;padding-top: 30px;padding-bottom: 30px\">" +
                                    "<div style=\"width: 60px;float: left;padding-right: 25px;height: 50px;line-height: 50px\">" +
                                        "<img style=\"height: 50px;width: 50px;border-radius:50%; \" src=\"../static/image/headImg/"+_this.targetUser+".jpg\">" +
                                    "</div>" +
                                    "<div style=\"float: left;background-color: cornflowerblue;border-radius: 4px;line-height: 24px;letter-spacing: 1px;max-width: 455px\">"
                                        +obj.message+
                                    "</div>" +
                                  "</div>"
                        //判断二者之间是否存在原来的聊天记录
                        if (obj.fromUserName===_this.targetUser){
                            var previousData = sessionStorage.getItem(_this.user.userName+"->"+_this.targetUser);
                            if (previousData!=null){
                                str = previousData + str
                            }
                            $("#content").html(str)
                        }
                        //更新聊天记录
                        /*
                        * 思考：如果第三个人王五给张三或者李四发送消息，而此时张三和李四之间正在发送消息
                        *      假如：王五给张三发送消息，那么张三正在和李四聊天，张三改怎么办？
                        *   1、判断张三接收的消息是否来自正在聊天的李四
                        *   1.1、是：保存+拼接展示
                        *   1.2、不是：直接保存
                        * */

                        sessionStorage.setItem(_this.user.userName+"->"+obj.fromUserName,str)

                    }
                }
                //websocket连接被关闭
                webSocket.onclose = function () {
                    
                }
            },

            //客户端向服务端发送消息
            //向某个用户发送消息
            sendMessageToTargetUser() {
                //将发送框的内容转为指定的消息格式
                var obj = {fromUserName: this.user.userName, toUserName: this.targetUser, message: this.textarea}
                var jsonStr = JSON.stringify(obj);
                var str = "<div style='float: right;width: 540px;padding-top: 30px;padding-bottom: 30px'>"+
                            "<div style='width: 60px;float: right;padding-left: 25px;height: 50px;line-height: 50px'>"+
                                "<img style='height: 50px;width: 50px;border-radius:50%;' src='../static/image/headImg/"+this.user.userName+".jpg'>"+
                            "</div>"+
                            "<div style='float: right;background-color: cornflowerblue;border-radius: 4px;line-height: 24px;letter-spacing: 1px;max-width: 455px'>"+
                                this.textarea+
                            "</div>"+
                            "</div>"
                console.log("自动调用了该方法：" + jsonStr);
                this.$webSocket.send(jsonStr)
                this.textarea = ""
                //对应发送方来说：两人之间的聊天记录
                var previousData = sessionStorage.getItem(this.user.userName+"->"+this.targetUser);
                if (previousData!=null){
                    str = previousData + str
                }
                $("#content").html(str);
                //更新聊天记录（当前用户->目标用户）
                sessionStorage.setItem(this.user.userName+"->"+this.targetUser,str)
            },
            //是否打开聊天室对话框
            openDialog(simpleUser) {
                console.log("进入该方法了吗？")
                this.chatOpenBoolean = false
                this.targetBoolean = true
                this.targetUser = simpleUser

                //获取聊天记录
                var previousData = sessionStorage.getItem(this.user.userName+"->"+this.targetUser);
                $("#content").html(previousData)
            },

        },
        created() {
            this.getUserInfo()
        }
    })
</script>
</html>